﻿using App.IBLL;
using App.Model.FileInfo;
using App.Model.MiddlewareModel;
using APP.DTO.ApplicationInfo;
using DataService.Core.Common;
using DataService.Core.ServiceDTO;
using DataService.Main;
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace App.BLL
{
    public class RequestResponseRecordBLL : IRequestResponseRecordBLL
    {

        public async Task SaveFileRecord(List<FileRecordInfo> list)
        {
            Task task = new Task(() =>
            {
                try
                {
                    string month = System.DateTime.Now.ToString("yyyyMM");
                    string filePath = SqliteDBFile($"FileRecord_{month}.db", FilePathHelper.BasePath, "TemplateFile.db", string.Empty);
                    using (var sqlitedb = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
                    {
                        string connectionString = string.Format("Data Source={0};", filePath);
                        sqlitedb.ConnectionString = connectionString;
                        DAL.Insert(list, sqlitedb);
                    }
                }
                catch (Exception)
                {

                    throw;
                }


            });
            task.Start();
            await task;
            task.Dispose();

        }


        /// <summary>
        /// 保存请求接口的记录
        /// </summary>
        public int SetRequestRecord(RequestRecord requestRecord)
        {
            string month = System.DateTime.Now.ToString("yyyyMM");
            string filePath = SqliteDBFile($"RequestRecord_{month}.db", FilePathHelper.BasePath, "TemplateData.db", ApplicationConfigDTO.SqlitePwd);
            using (var sqlitedb = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {
                string connectionString = string.Format("Data Source={0};", filePath);
                if (!string.IsNullOrEmpty(ApplicationConfigDTO.SqlitePwd))
                {
                    connectionString = $"{connectionString};Password={ApplicationConfigDTO.SqlitePwd};";
                }
                sqlitedb.ConnectionString = connectionString;
                return DAL.Insert(requestRecord, sqlitedb);
            }
        }

        public LoginUser GetLoginUserByToken(string token)
        {
            string month = System.DateTime.Now.ToString("yyyyMM");
            string filePath = SqliteDBFile($"RequestRecord_{month}.db", FilePathHelper.BasePath, "TemplateData.db", ApplicationConfigDTO.SqlitePwd);
            using (var sqlitedb = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {
                string connectionString = string.Format("Data Source={0};", filePath);
                if (!string.IsNullOrEmpty(ApplicationConfigDTO.SqlitePwd))
                {
                    connectionString = $"{connectionString};Password={ApplicationConfigDTO.SqlitePwd};";
                }
                sqlitedb.ConnectionString = connectionString;
                LoginUser loginUser = DAL.QueryModel<LoginUser>(x => x.LoginToken == token, sqlitedb);
                return loginUser;
            }
        }


        public ImplementRecord GetImplementRecordByToken(string token)
        {
            string month = System.DateTime.Now.ToString("yyyyMM");
            string filePath = SqliteDBFile($"RequestRecord_{month}.db", FilePathHelper.BasePath, "TemplateData.db", ApplicationConfigDTO.SqlitePwd);
            using (var sqlitedb = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {
                string connectionString = string.Format("Data Source={0};", filePath);
                if (!string.IsNullOrEmpty(ApplicationConfigDTO.SqlitePwd))
                {
                    connectionString = $"{connectionString};Password={ApplicationConfigDTO.SqlitePwd};";
                }
                sqlitedb.ConnectionString = connectionString;
                ImplementRecord implementRecord = DAL.QueryModel<ImplementRecord>(x => x.Token == token, sqlitedb);
                return implementRecord;
            }
        }


        private string SqliteDBFile(string dbName, string tempPath, string templateName, string dbpwd)
        {
            tempPath = tempPath + System.DateTime.Now.ToString("yyyyMM") + "\\";
            if (Directory.Exists(tempPath) == false)
            {
                Directory.CreateDirectory(tempPath);
            }
            string dbFile = Path.Combine(tempPath, dbName);
            if (!System.IO.File.Exists(dbFile))  //若不存在db则创建db文件
            {
                CopyTemplateToNewDB(dbFile, templateName);
                //FileStream fs = File.Create(dbFile);
                //fs.Close();
                //string connectionString = string.Format("Data Source={0}", dbFile);
                //using (IDbConnection conn = new SQLiteConnection(connectionString))
                //{
                //    conn.Open();
                //    CreateSqliteDBTable(conn);
                //}
                //设置密码
                string connectionString = string.Format("Data Source={0};", dbFile);
                using (SQLiteConnection conn = new SQLiteConnection(connectionString))
                {
                    if (!string.IsNullOrEmpty(dbpwd))
                    {
                        conn.Open();
                        conn.ChangePassword(dbpwd);//设置密码
                        conn.Close();
                    }
                }
            }
            return dbFile;
        }
        /// <summary>
        /// 模板数据生成的sqlte数据库
        /// </summary>
        /// <param name="newDB">新sqlite全路径</param>
        private void CopyTemplateToNewDB(string newDB, string templateName)
        {

            string fullPath = Path.Combine(FilePathHelper.BasePath, $"ModelFile\\{templateName}");
            File.Copy(fullPath, newDB, true);
        }


    }
}
